package org.vectrics.recruiter.xmlweb;

import org.vectrics.SystemException;
import org.vectrics.common.util.DateUtil;
import org.vectrics.common.util.StringUtils;
import org.vectrics.dataweb.WebServiceAction;
import org.vectrics.employee.Employee;
import org.vectrics.employee.JobTermReference;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.JobTerm;
import org.vectrics.struts.Request;
import org.w3c.dom.Element;

public class StateEmployeeWebService extends WebServiceAction {
    public static String COMMAND = "get.employee.condition";

    @Override
    public void getData(final Request request, final String command, final Element requestElement,
            final Element responseElement) {
        log.info("Command: " + command);
        Element dataElement = getDataElement(responseElement);
        // Si el comando es correcto
        if (command.equals(COMMAND)) {
            // Busco los parametros
            String stateId = request.getParameter("state");
            String idEmployee = request.getParameter("id");
            // Si son nulos devuelvo error.
            if (!StringUtils.isNullOrBlank(stateId) && !StringUtils.isNullOrBlank(idEmployee)) {
                // Recupero el empleado
                Employee employee = RecruitServiceLocator.getCompanyService().findEmployee(new Long(idEmployee));
                log.info("JobTerm search (for idEmployee) - found JobTerm: " + employee);

                Element referenceElement = responseElement.getOwnerDocument().createElement("reference");
                // Recupero el jobTerm
                JobTerm jobTerm = RecruitServiceLocator.getJobProvider().findJobTermForCode(stateId);
                // Si alguno es nulo devuelvo error
                if (employee == null)
                    throw new SystemException("employee not found");
                if (jobTerm == null)
                    throw new SystemException("jobTerm not found");
                // Si el no empleado tiene un estado, lleno el element con los
                // datos del jobTerm
                if (employee.getCurrentStatus() != null) {
                    // si son iguales los estados devuelvo statusEquals en true
                    if (!employee.getCurrentStatus().getStatusType().getId().equals(jobTerm.getId())) {
                        JobTermReference reference = RecruitServiceLocator.getCompanyService().findJobTermReference(
                                jobTerm, employee.getCurrentStatus().getStatusType());

                        // Si no encuentra la referencia significa que no existe
                        // el camino, la vista no deberia hacer nada.
                        if (reference != null) {
                            // lleno el elemento segun los datos del
                            // JobTermReference
                            this.referenceToElement(reference, referenceElement);
                        } else {
                            referenceElement.setAttribute("statusExist", "false");
                            referenceElement.setAttribute("statusEquals", "false");
                            referenceElement.setAttribute("isRequieredDate", "false");
                        }
                    } else {
                        // lleno el elemento segun los datos del jobTerm, tengo
                        // que devolver la fecha ya que se deve cargar en la
                        // vista
                        referenceElement.setAttribute("statusExist", "true");
                        referenceElement.setAttribute("statusEquals", "true");
                        this.referenceToElement(jobTerm, referenceElement);
                        referenceElement.setAttribute("date",
                                DateUtil.getFechaFormateada(employee.getCurrentStatus().getDateStart()));
                    }
                } else {
                    // lleno el elemento segun los datos del jobTerm
                    referenceElement.setAttribute("statusExist", "false");
                    referenceElement.setAttribute("statusEquals", "false");
                    this.referenceToElement(jobTerm, referenceElement);
                }

                log.info("JobTerm search (for Id) - found JobTerm: " + jobTerm);
                // Devuelvo el elemento a la vista
                dataElement.appendChild(referenceElement);
            } else
                throw new SystemException("State or Id is null or Blank");
        } else
            throw new SystemException("Do not know how to handle command: " + command);
    }

    private void referenceToElement(final JobTerm jobTerm, final Element referenceElement) {
        if (jobTerm.getCode().trim().equalsIgnoreCase("RD")) {
            referenceElement.setAttribute("phase",
                    CoreServiceLocator.getPhraseProvider().getMessage("prompt.employee.firstDay", getLocale()));
            referenceElement.setAttribute("isRequieredDate", "true");
        } else {
            if (jobTerm.getCode().trim().equalsIgnoreCase("not.employee")) {
                referenceElement.setAttribute("phase",
                        CoreServiceLocator.getPhraseProvider().getMessage("prompt.employee.date.end", getLocale()));
                // referenceElement.setAttribute("isRequieredDate", "true");
                referenceElement.setAttribute("isRequieredDate", "false");
            } else {
                referenceElement.setAttribute("isRequieredDate", "false");
            }
        }
    }

    private void referenceToElement(final JobTermReference reference, final Element referenceElement) {
        referenceElement.setAttribute("statusExist", "true");
        referenceElement.setAttribute("statusEquals", "false");
        referenceElement.setAttribute("id", reference.getId().toString());
        referenceElement.setAttribute("phase",
                CoreServiceLocator.getPhraseProvider().getMessage(reference.getPhraseDate(), getLocale()));
        referenceElement.setAttribute("isRequieredDate", Boolean.toString(reference.isRequieredDate()));
    }

}
